const db = require('../config/db');
const { success, fail } = require('../utils/response');

exports.getCategories = async (req, res) => {
  const [rows] = await db.query('SELECT * FROM Category');
  res.json(success(rows));
};

exports.getProducts = async (req, res) => {
  const { category_id } = req.query;
  const [rows] = category_id
    ? await db.query('SELECT * FROM Product WHERE category_id=?', [category_id])
    : await db.query('SELECT * FROM Product');
  res.json(success(rows));
};

exports.uploadProductImage = async (req, res) => {
  try {
    if (!req.file) {
      return res.json(fail('请选择要上传的图片'));
    }
    
    const { productId } = req.body;
    const { id } = req.params;
    
    if (!productId && !id) {
      return res.json(fail('请提供商品ID'));
    }
    
    const product_id = productId || id;
    
    // 读取上传文件并转为 Base64（适配 LONGTEXT）
    const fs = require('fs');
    const mime = req.file.mimetype || 'image/jpeg';
    const base64 = fs.readFileSync(req.file.path, { encoding: 'base64' });
    const dataUri = `data:${mime};base64,${base64}`;
    
    // 将图片存储为 LONGTEXT（Data URI）
    await db.query('UPDATE Product SET image=? WHERE id=?', [dataUri, product_id]);
    
    // 删除临时文件
    fs.unlinkSync(req.file.path);
    
    res.json(success({ message: '图片上传成功' }));
  } catch (error) {
    console.error('图片上传失败:', error);
    res.json(fail('图片上传失败'));
  }
};

exports.getProductById = async (req, res) => {
  const { id } = req.params;
  const [rows] = await db.query('SELECT * FROM product WHERE id=?', [id]);
  if (!rows.length) return res.json(fail('商品不存在'));
  
  const product = rows[0];
  
  // 兼容历史 MEDIUMBLOB：如是 Buffer，则转为 Base64 Data URI
  if (product.image && Buffer.isBuffer(product.image)) {
    const base64Image = product.image.toString('base64');
    const mime = 'image/jpeg';
    product.image = `data:${mime};base64,${base64Image}`;
  }
  
  res.json(success(product));
};

